<template>
  <div class="app-container">
    <PageTools type="info">
      <template #before>
        <span>共166条记录</span>
      </template>
      <template #after>
        <el-button
          v-permission="'import_excell11'"
          size="small"

          type="warning"
          @click="$router.push('/import?type=user')"
        >导入</el-button>
        <el-button size="small" type="danger" @click="handleExport">导出</el-button>
        <el-button size="small" type="primary" @click="handleClose">新增员工</el-button>
      </template>
    </PageTools>
    <!-- 放置表格和分页 -->
    <el-card>
      <el-table v-loading="loading" border :data="list">
        <el-table-column label="序号" sortable="" width="80" type="index" />
        <el-table-column label="姓名" prop="username" />
        <el-table-column label="头像">
          <template slot-scope="{row}">

            <img
              v-imgError="require('@/assets/bigUserHeader.png')"
              :src=" row.staffPhoto"
              alt=""
              style="width:100px;height:100px;border-radius:50%"
              @click="showDiolag(row.staffPhoto)"
            >

          </template>
        </el-table-column>
        <el-table-column label="工号" prop="workNumber" />
        <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatterEmployment" />
        <el-table-column label="部门" prop="departmentName" />
        <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
          <template slot-scope="{row}">
            {{ row.timeOfEntry | formatDate }}

          </template>
        </el-table-column>
        <el-table-column label="账户状态" prop="enableState">
          <template slot-scope="{row}">
            <el-switch :value="row.enableState ===1" active-color="red" inactive-color="red" />
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="280">
          <template slot-scope="{row}">
            <el-button
              type="text"
              size="small"
              @click="$router.push(`/employees/detail/${row.id}`)"
            >
              查看</el-button>
            <el-button type="text" size="small">转正</el-button>
            <el-button type="text" size="small">调岗</el-button>
            <el-button type="text" size="small">离职</el-button>
            <el-button type="text" size="small" @click="handleOpen(row.id)">角色</el-button>
            <el-button type="text" size="small" @click="handleDel(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row type="flex" justify="end" align="middle" style="height: 60px">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next"
          :current-page.sync="page.page"
          :page-size.sync="page.size"
          :page-sizes="[2,5,10,20]"
          :total="total"
          @current-change="getEmployeeList"
          @size-change="getEmployeeList"
        />
      </el-row>
    </el-card>
    <!-- 新增弹窗 -->
    <Employees :dialog-visible.sync="dialogVisible" />
    <el-dialog title="头像二维码" :visible.sync="ercodeDialog">
      <canvas id="canvas" ref="canvas" />
    </el-dialog>
    <AssignRole ref="assign" :dialog-visible.sync="AssignRole" :user-id="userId" />
  </div>
</template>

<script>
import { getRoleListAPI } from '@/api/setting'
import { getUserDetailByIdAPI } from '@/api/user'
import Employees from './components/employees'
import { getEmployeeListAPI, delEmployeApi } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import QrCode from 'qrcode'
import AssignRole from './components/assign-role.vue'
export default {
  name: 'Employess',
  components: {
    Employees,
    AssignRole
  },
  props: {},
  data() {
    return {
      page: {
        page: 1,
        size: 10
      },
      list: [],
      total: 0,
      loading: false,
      dialogVisible: false,
      ercodeDialog: false,
      AssignRole: false,
      userId: ''

    }
  },
  computed: {},
  watch: {},
  created() {
    this.getEmployeeList()
  },
  mounted() {
    console.log(this.$route.params.id)
  },
  methods: {
    async getEmployeeList() {
      try {
        this.loading = true
        const { rows, total } = await getEmployeeListAPI(this.page)
        // console.log(rows)
        this.list = rows
        this.total = total
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },
    formatterEmployment(row, column, cellValue) {
      const obj = EmployeeEnum.hireType.find(ele => ele.id === +cellValue)
      return obj && obj.value || '非正式'
    },
    handleClose() {
      this.dialogVisible = true
    },
    async handleDel(row) {
      try {
        await this.$confirm('确认是否删除该员工', '提示', {
          type: 'warning'
        }

        )
        await delEmployeApi(row.id)
        this.$message.success('删除成功')
        this.getEmployeeList()
      } catch (error) {
        console.log(error)
      }
    },
    handleExport() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      import('@/vendor/Export2Excel').then(excel => {
        // excel.export_json_to_excel({ // 可以把数据 转换Excel
        //   header: ['姓名', '手机号', '入职日期', '聘用形式'], // 表头 必填
        //   data: [['张三', '13399999', '2020-2020-2020', '正式']], // 具体数据 必填
        //   filename: 'excel-list', // 非必填
        //   autoWidth: true, // 非必填
        //   bookType: 'xlsx' // 非必填
        // })
        debugger
        const arr1 = this.list.map(ele => {
          const arr = []
          Object.values(headers).forEach(item => {
            if (item === 'timeOfEntry' || item === 'correctionTime') {
              arr.push(this.$options.filters.formatDate(ele[item]))
            } else if (item === 'formOfEmployment') {
              const obj = EmployeeEnum.hireType.find(ele1 => { return ele1.id === +ele[item] })
              arr.push(obj && obj.value || '非正式')
            } else {
              arr.push(ele[item])
            }
          })
          return arr
        })
        console.log(arr1)
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          data: arr1, // 具体数据 必填
          filename: '员工', // 非必填
          autoWidth: true, // 非必填
          multiHeader: [['姓名', '主要信息', '', '', '', '', '']],
          merges: ['A1:A2', 'B1:G1'],
          bookType: 'xlsx' // 非必填
        })
      })
    },
    async showDiolag(info) {
      if (!info) {
        this.$message.warning('该用户还未设置头像')
      }
      this.ercodeDialog = true
      await this.$nextTick()
      QrCode.toCanvas(this.$refs.canvas, info)
    },
    async  handleOpen(id) {
      this.AssignRole = true
      const { rows } = await getRoleListAPI()
      const roleIds = await getUserDetailByIdAPI(id)
      this.$refs.assign.roleIds = roleIds
      this.userId = id
      this.$refs.assign.roleList = rows
    }
  }
}

</script>

<style scoped>

</style>
